﻿using FlashGameSite.Manager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FlashGameSite
{
    public partial class FormGamesByCategory : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString.AllKeys.Contains("cat"))
                {
                    int categoryId = Convert.ToInt32(Request.QueryString["cat"]);
                    htitle.InnerText = string.Format("Games for {0} category", GetCategoryName(categoryId));
                    LoadGamesByCategory(categoryId);
                }
                else
                {
                    htitle.InnerText = "All Games";
                    LoadGamesByCategory(0);
                }
            }
        }

        private string GetCategoryName(int categoryId)
        {
            string categoryName = string.Empty;
            using (FlashGamesDataContext dataContext = new FlashGamesDataContext())
            {
                var result = from obj in dataContext.Categories
                             where obj.CategoryID == categoryId
                             select new { obj.Title };

                foreach (var item in result)
                {
                    categoryName = item.Title;
                }
            }

            return categoryName;
        }

        private void LoadGamesByCategory(int categoryId)
        {
            int? totalPage=0;
           
            using (FlashGamesDataContext dataContext = new FlashGamesDataContext())
            {
                if (categoryId > 0)
                {
                    GridGames.DataSource = dataContext.GetGamesByCategory(categoryId, 1, 54, ref totalPage);
                }
                else
                {
                    GridGames.DataSource = dataContext.GetAllGames(1, 54, ref totalPage);
                }

                GridGames.DataBind();
            }
        }
    }
}